package com.example.demo.core.security;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.ArrayList;

public class JWTUtil {
    private String secret;

    public static boolean verify(String name,String token,String secret)
    {
        try{
            Algorithm algorithm=Algorithm.HMAC256(secret);
            JWTVerifier verifier=JWT.require(algorithm).withClaim("name", name).build();
            DecodedJWT jwt=verifier.verify(token);
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }

    public static String getName(String token)
    {
        try {
            DecodedJWT jwt=JWT.decode(token);
            return jwt.getClaim("name").asString();
        }
        catch (Exception e)
        {
            return null;
        }
    }

    public static String getRole(String token)
    {
        try {
            DecodedJWT jwt=JWT.decode(token);
            return jwt.getClaim("role").asString();
        }
        catch (Exception e)
        {
            return null;
        }
    }

    public static String getId(String token)
    {
        try {
            DecodedJWT jwt=JWT.decode(token);
            return jwt.getClaim("id").asString();
        }
        catch (Exception e)
        {
            return null;
        }
    }

    public static String getTable(String token)
    {
        try {
            DecodedJWT jwt=JWT.decode(token);
            return jwt.getClaim("table").asString();
        }
        catch (Exception e)
        {
            return null;
        }
    }

    public static String getToken(String id,String name,String role,String table,String secret)
    {
        try{
            Algorithm algorithm=Algorithm.HMAC256(secret);
            return JWT.create().withClaim("name",name).withClaim("role",role).withClaim("id",id).withClaim("table",table).sign(algorithm);
        }
        catch (Exception e)
        {
            return null;
        }
    }
}
